#include "Device.h"
namespace android::wmark
{
    Device::Device(string dev):mDev(dev)
    {
        openDev();
    }

    Device::Device(string dev, int openFlag):mDev(dev)
    {
        openDev(openFlag);
    }

    Device::~Device()
    {
        if (getFd() > 0)
        {
            close(getFd());
            mFd = -1;
        }
    }

    int Device::openDev()
    {

        int fd;
        if (mFd > 0)
        {
            return 0;
        }
        fd = open(mDev.c_str(), O_RDWR);
        if (fd == -1)
        {
            ALOGE("%s open failure\n", mDev.c_str());
            return -1;
        }
        mFd = fd;
        return 0;
    }

    int Device::openDev(int openFlag)
    {
        int fd;
        if (mFd > 0)
        {
            return 0;
        }

        fd = open(mDev.c_str(), openFlag);
        if (fd == -1)
        {
            ALOGE("%s open failure\n", mDev.c_str());
            return -1;
        }
        mFd = fd;
        return 0;
    }

    int Device::getFd()
    {
        mMutex.lock();
        while (mFd <= 0)
        {
            openDev();
        }
        mMutex.unlock();

        return mFd;
    }
}